
package com.mego.tzadd.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.Jtdetailinfo;
import com.mego.tzadd.database.dbmodel.Jtinfo;
import com.mego.tzadd.database.manager.JtinfoCenter;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.base.BaseView;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.util.JSON;


public class Fragment0 extends BaseFragment implements AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "Fragment0";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static Fragment0 createInstance() {
        return new Fragment0();
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.fragment0);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    private ListView lv_jt;

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreateView方法内调用
        lv_jt = (ListView) findViewById(R.id.lv_jt);
    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (list == null) {
            return;
        }
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_jt.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> jtlist;
    private ArrayList<Jtinfo> mJtList = new ArrayList<Jtinfo>();

    boolean _isloading = false;

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreate方法内调用

    }

    void doSearch(final boolean isFirst) {
        if (_isloading) {
            return;
        }

        _isloading = true;
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        if (isFirst) {
            showProgressDialog(R.string.loading);
        }

        mJtList.clear();
        long adminid = SystemCenter.getInstance().adminid;

        try {
            HttpRequest.jtlist(adminid, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject a = jsonArray.getJSONObject(i);
                            Jtinfo jt = new Jtinfo(null, a.getString("name"), a.getInteger("money"), a.getInteger("isonline"), a.getInteger("auto_switch"), a.getLong("id"), a.getInteger("order"), a.getInteger("shunyi"));
                            mJtList.add(jt);
                        }

                        if (isFirst) {
                            jtlist = getList();
                            setList(jtlist);
                        } else {
                            adapter.notifyListDataSetChanged();
                        }
                    } else {
                        showShortToast("獲取機台列表失敗！ " + SystemCenter.getInstance().adminid);
                    }
                    _isloading = false;
                    if (isFirst) {
                        dismissProgressDialog();
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            if (isFirst) {
                dismissProgressDialog();
            }
            _isloading = false;
        }
    }

    protected List<Entry<Integer, String>> getList() {
        jtlist = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < mJtList.size(); i++) {
            jtlist.add(new Entry<Integer, String>(i, ""));
        }
        return jtlist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用

    }

    boolean _isdoing = false;
    private void selectJt(Jtinfo a) {
        if (a == null) {
            return;
        }

        if (_isdoing) {
            return;
        }
        _isdoing = true;

        JtinfoCenter.getInstance().jtinfo = a;
        jtdetailinfo();

    }

    private void jtdetailinfo() {
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.jtdetailinfo(JtinfoCenter.getInstance().jtinfo.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject a = jsonObject.getJSONObject("data");
                        Jtdetailinfo jt = new Jtdetailinfo(null, a.getLong("id"), a.getInteger("isonline"),
                                a.getString("name"), a.getInteger("bjje"),
                                a.getInteger("toubi_switch"), a.getInteger("chuhuo_switch"),
                                a.getInteger("auto_switch"), a.getInteger("time"),
                                a.getInteger("money"), a.getInteger("zdxb"), a.getString("jt_serial"),
                                a.getInteger("cost"), a.getString("expiration_date"), a.getString("start_date"));
                        JtinfoCenter.getInstance().jtdetailinfo = jt;

                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        Date curDate = new Date();
                        String strDate = formatter.format(curDate);
                        if (strDate.compareTo(jt.getExpiration_date()) > 0) {
//                            Toast.makeText(getContext(), "此機台 " + jt.getExpiration_date() + " 到期！", Toast.LENGTH_LONG).show();
                            Toast.makeText(getContext(), "此機台已到期，無法進行操作!", Toast.LENGTH_LONG).show();
                        } else {
                            startActivityForResult(JtInfoTabActivity.createIntent(getContext()), 666);
                        }
                    } else {
                        showShortToast("獲取詳情失敗！");
                    }
                    dismissProgressDialog();
                    _isdoing = false;
                }
            });
        } catch (Exception e1) {
            dismissProgressDialog();
            showShortToast("獲取詳情失敗！");
            _isdoing = false;
        }
    }

    Jtinfo _xbjt; //强制消保的机台

    private void qzxb(Jtinfo a) {
        if (a == null) {
            return;
        }
        if (a.isQzxb) {
            showShortToast("此機台[" + a.getName() + "]正在強制消保中...");
            return;
        }
        _xbjt = a;
        new AlertDialog(context, "", "請確認對此機台強制消保 \n [" + a.getName() + "] ?", "確認", "取消", 11, this).show();
    }

    private void doQzxb() {
        _xbjt.isQzxb = true;
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.qzxb(_xbjt.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        showShortToast("機台設置成功訊息！");
                        _xbjt.setMoney(0);
                        setList(jtlist);
                    } else {
                        showShortToast("機台無回應訊息！");
                    }
                    _xbjt.isQzxb = false;
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
            _xbjt.isQzxb = false;
        }
    }

    Jtinfo _zxjt; //自动消保的机台

    private void zdxb(Jtinfo a) {
        if (a == null) {
            return;
        }
        _zxjt = a;
        String b = "開啟";
        if (a.getAuto_switch() == 1) {
            b = "關閉";
        }
        new AlertDialog(context, "", "請確認" + b + " [" + a.getName() + "] 此機台自動消保 ?", "確認", "取消", 13, this).show();
    }

    private void doZdxb() {
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.zdxb(_zxjt.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        showShortToast("自动消保成功！");
                        if (_zxjt.getAuto_switch() == 0) {
                            _zxjt.setAuto_switch(1);
                        } else {
                            _zxjt.setAuto_switch(0);
                        }
                        setList(jtlist);
                    } else {
                        showShortToast("自动消保失败！");
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    boolean _isDojtorder = false;

    private void dojtorder(long jtid, int max, final int orderop) {

        _isDojtorder = true;
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.jtorder(jtid, max, orderop, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    dismissProgressDialog();
                    if (code == 1) {
                        if (orderop == 0) {
                            showShortToast("已取消此機台置頂!");
                        } else {
                            showShortToast("已將此機台置頂!");
                        }
                        initData();
                    } else {
                        showShortToast("自机台顺序修改失败！");
                    }
                    _isDojtorder = false;
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
            _isDojtorder = false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }
        if (requestCode == 11) {
            //强制消保 qzxb()
            doQzxb();
        } else if (requestCode == 13) {
            //自动消保 zdxb()
            doZdxb();
        }
    }

    int _move = 0;
    int _moveindex = 0;

    public class DemoView extends BaseView<Entry<Integer, String>> implements View.OnClickListener {
        private static final String TAG = "DemoView";

        public DemoView(Activity context, ViewGroup parent) {
            super(context, R.layout.jt_view, parent);  //TODO demo_view改为你所需要的layout文件
        }

        //示例代码<<<<<<<<<<<<<<<<
        public ImageView iv_zdxb;
        public TextView tv_jtame;
        public TextView tv_zxzt;
        public TextView tv_mqbl;
        public TextView tv_qzxb;
        public TextView tv_shunyi;

        //示例代码>>>>>>>>>>>>>>>>
        @Override
        public View createView() {

            //示例代码<<<<<<<<<<<<<<<<
            iv_zdxb = findView(R.id.iv_zdxb, this);
            tv_jtame = findView(R.id.tv_jtame);
            tv_zxzt = findView(R.id.tv_zxzt);
            tv_mqbl = findView(R.id.tv_mqbl);
            tv_shunyi = findView(R.id.tv_shunyi);
            tv_qzxb = findView(R.id.tv_qzxb, this);

            findView(R.id.ctrl_jtone, this);
//            //示例代码>>>>>>>>>>>>>>>>
//            findView(R.id.ctrl_jtone).setOnLongClickListener(myLongClickListener);
//            tv_qzxb.setOnLongClickListener(myLongClickListener);

//            findView(R.id.ctrl_jtone).setOnTouchListener(new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View v, MotionEvent event) {
//                    if (data == null) {
//                        return false;
//                    }
//                    int index = data.getKey();
//                    if (index >= mJtList.size()) {
//                        return false;
//                    }
//
//                    int action = event.getAction();
//                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                        _moveindex = index;
//                        _move = 0;
//                    }
//                    if (event.getAction() == MotionEvent.ACTION_MOVE) {
//                        if (_moveindex == index) {
//                            _move++;
//                        } else {
//                            _move = 0;
//                        }
//                        if (_move > 2) {
//                            Jtinfo a = mJtList.get(index);
//                            selectJt(a);
//                            _move = -1000;
//                        }
//                        return true;
//                    }
//                    return false;
//                }
//            });

            return super.createView();
        }

        private View.OnLongClickListener myLongClickListener = new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (data == null || _isDojtorder) {
                    return false;
                }

                int index = data.getKey();
                if (index >= mJtList.size()) {
                    return false;
                }
                Jtinfo a = mJtList.get(index);

                switch (v.getId()) {
                    case R.id.ctrl_jtone:
                        int orderop = 1;
                        int max = 0;
                        for (int i = 0; i < mJtList.size(); i++) {
                            int order = mJtList.get(i).getOrder();
                            if (order > max) {
                                max = order;
                            }
                        }
                        if (a.getOrder() == max && max > 0) {
                            orderop = 0;
                        }
                        dojtorder(a.getJtid(), max, orderop);
                        break;
                    case R.id.tv_qzxb:
                        qzxb(a);
                        break;
                    default:
                        break;
                }

                return true;
            }
        };

        @Override
        public void bindView(Entry<Integer, String> data_) {
            //示例代码<<<<<<<<<<<<<<<<
            super.bindView(data_ != null ? data_ : new Entry<Integer, String>());

//            itemView.setBackgroundResource(selected ? R.drawable.alpha3 : R.drawable.white_to_alpha);

            int index = data.getKey();
            if (index >= 0 && index < mJtList.size()) {
                Jtinfo a = mJtList.get(index);
                tv_jtame.setText(a.getName());
                if (a.getIsonline() == 1) {
                    tv_zxzt.setText("在線");
                    tv_zxzt.setTextColor(Color.parseColor("#3FCD00"));
                } else {
                    tv_zxzt.setText("離線");
                    tv_zxzt.setTextColor(Color.parseColor("#FE4545"));
                }
                tv_mqbl.setText(a.getMoney() + "");
                iv_zdxb.setImageResource(a.getAuto_switch() == 1 ? R.mipmap.btn_turn_on : R.mipmap.btn_turn_off);

                if (a.getShunyi() > 0) {
                    tv_shunyi.setTextColor(Color.parseColor("#0000FF"));
                } else {
                    tv_shunyi.setTextColor(Color.parseColor("#FE4545"));
                }
                tv_shunyi.setText(a.getShunyi() + "");
            }
            //示例代码>>>>>>>>>>>>>>>>
        }


        //示例代码<<<<<<<<<<<<<<<<
        @Override
        public void onClick(View v) {
            if (data == null) {
                return;
            }
            int index = data.getKey();
            if (index >= mJtList.size()) {
                return;
            }
            Jtinfo a = mJtList.get(index);
            switch (v.getId()) {
                case R.id.iv_zdxb:
                    zdxb(a);
//                    bindView(data);
//                    if (onDataChangedListener != null) {
//                        onDataChangedListener.onDataChanged();
//                    }
                    break;
                case R.id.ctrl_jtone:
                    selectJt(a);
                    break;
                case R.id.tv_qzxb:
                    qzxb(a);
                    break;
                default:
                    break;
            }
        }
        //示例代码>>>>>>>>>>>>>>>>


    }

    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>, DemoView> {

        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public DemoView createView(int position, ViewGroup parent) {
            return new DemoView(context, parent);
        }

        @Override
        public long getItemId(int position) {
            return getItem(position).getId();
        }


    }


    @Override
    public void onResume() {
        super.onResume();
        doSearch(true);
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    public void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        doSearch(false);

    }

    @Override
    public void onTimerStop() {

    }

}